<?php

namespace plugin\admin\app\controller\common;

use plugin\admin\app\common\xbuilder\XBuilderList;
use support\Request;

trait Crud
{

    protected $model = null;

    public function getApiTableData(Request $request){
        $status_model = $this->model;
        $keyword = $request->input('id','');
        $map[] = ['id','like', '%' . $keyword . '%'];
        $map[] = ['status','>=', '-1'];
        $orderBy = $request->input('orderBy', 'updated_at') ?: 'updated_at';
        $orderDir = $request->input('orderBy', 'desc') ?: 'desc';
        $orderArr = [
            'id' => 'desc',
            $orderBy => $orderDir
        ];
        $data_list = $status_model
            ->where($map)
            ->order($orderArr)
            ->paginate();
        $get_table_data = XBuilderList::handleTableData($data_list);
//        return json(['status' => 0, 'data' => $get_table_data, 'msg' => '请求成功']);
        return $this->resSucess('',$get_table_data);
    }

    /**
     * 设置一条或者多条数据的状态
     * @param Request $request
     * @return \support\Response
     * @throws \think\db\exception\DbException
     */
    public function setStatus(Request $request)
    {
        $model = $this->model;
        $ids = $request->input('ids');
        $status = $request->input('status');
        if(empty($ids)){
            return $this->resError('请选择要操作的数据');
        }
        // 获取主键
        $model_primary_key = $model->getPk();
        // 获取id
        $ids = is_array($ids) ? implode(',', $ids) : $ids;
        $map[] = [$model_primary_key,'in', $ids];
        switch ($status) {
            case 'forbid': // 禁用条目
                $data['status'] = 0;
                return $this->editRow(
                    $data,
                    $map,
                    array('success' => '禁用成功', 'error' => '禁用失败')
                );
                break;
            case 'resume': // 启用条目
                $data['status'] = 1;
                return $this->editRow(
                    $data,
                    $map,
                    array('success' => '启用成功', 'error' => '启用失败')
                );
                break;
            case 'recycle': // 移动至回收站
                // 查询当前删除的项目是否有子代
                if (in_array('pid', $model->getTableFields())) {
                    $count = $model->where(['pid','in',$ids])->count();
                    if ($count > 0) {
                        return $this->resError('无法删除，存在子项目！');
                    }
                }

                // 标记删除
                $data['status'] = -1;
                return $this->editRow(
                    $data,
                    $map,
                    array('success' => '成功移至回收站', 'error' => '回收失败')
                );
                break;
            case 'restore': // 从回收站还原
                $data['status'] = 1;
                return $this->editRow(
                    $data,
                    $map,
                    array('success' => '恢复成功', 'error' => '恢复失败')
                );
                break;
            case 'delete': // 删除记录
                // 查询当前删除的项目是否有子代
                // 查询当前删除的项目是否有子代
                if (in_array('pid', $model->getTableFields())) {
                    $count = $model->where(['pid','in',$ids])->count();
                    if ($count > 0) {
                        return $this->resError('无法删除，存在子项目！');
                    }
                }

                // 删除记录
                $result = $model->where($map)->delete();
                if ($result) {
                    return $this->resSucess('删除成功，不可恢复！');
                } else {
                    return $this->resError('删除失败');
                }
                break;
            default:
                return $this->resError('参数错误');
                break;
        }
    }
    final protected function editRow($data, $map, $msg)
    {
        $msg = array_merge(
            array(
                'success' => '操作成功！',
                'error' => '操作失败！',
            ),
            (array)$msg
        );
        $model = $this->model;
        $result = $model->where($map)->replace()->save($data);
        if ($result) {
            return $this->resSucess($msg['success']);
        } else {
            return $this->resError($msg['error']);
        }
    }

    protected function getFormatTree($items)
    {
        $items_map = [];
        foreach ($items as $item) {
            $items_map[$item->id] = [
                'label' => $item->title ?? $item->name ?? $item->id,
                'value' => (string)$item->id,
                'key' => (string)$item->id,
                'pid' => $item->pid,
            ];
        }
        $formatted_items = [];
        foreach ($items_map as $index => $item) {
            if ($item['pid'] && isset($items_map[$item['pid']])) {
                $items_map[$item['pid']]['children'][] = &$items_map[$index];
            }
        }
        foreach ($items_map as $item) {
            if (!$item['pid']) {
                $formatted_items[] = $item;
            }
        }
        return $formatted_items;
    }

    protected function resSucess($msg = '数据请求成功', $data = []){
        $msg = $msg ?: '数据请求成功';
        if(is_array($msg)){
            $value = array_values($msg);
            $msg = implode('<br/>',$value);
        }
        return $this->json( 0, $msg, $data);
    }
    protected function resError($msg = '数据请求失败', $data = []){
        $msg = $msg ?: '数据请求失败';
        if(is_array($msg)){
            $value = array_values($msg);
            $msg = implode('<br/>',$value);
        }
        return $this->json( 500, $msg, $data);
    }
    protected function json(int $code, string $msg = 'ok', mixed $data = [])
    {
        return json(['code' => $code, 'data' => $data, 'msg' => $msg]);
    }

}
